//
//  RAPSearchField.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 12/27/15.
//  Copyright © 2015 RendezvousAuParadis. All rights reserved.
//

import UIKit

class RAPSearchField: UIView {
    @IBOutlet weak var searchFieldTrailingConstraint: NSLayoutConstraint!

    @IBOutlet weak var searchField: UITextField!
    @IBOutlet weak var cancelButton: UIButton!
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */

    /**
    开始编辑时调用
    */
    @IBAction func searchFieldBeganEditing(sender: AnyObject) {
        searchFieldTrailingConstraint.constant = cancelButton.frame.size.width
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.layoutIfNeeded()
        }
    }
    
    override func awakeFromNib() {
        let magView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        magView.frame.size = CGSize(width: searchField.bounds.height, height: searchField.bounds.height)
        magView.contentMode = .Center
        
        
        searchField.leftView = magView
        searchField.leftViewMode = .Always
        
        searchField.layer.borderWidth = 2
        searchField.layer.borderColor = UIColor.grayColor().CGColor
        searchField.layer.cornerRadius = 5
        
    }
    
    /**
    点击取消按钮时调用
    */
    @IBAction func cancelButtonClicked(sender: AnyObject) {
        // 清空text field
        searchField.text = ""
        // 退出第一响应者
        endEditing(true)
        
        /*
        注意，对约束的改变不会出发UIView的动画，需要将当前view标记为需要重绘制，
        从而出发动画
        */
        self.searchFieldTrailingConstraint.constant = 0
        UIView.animateWithDuration(0.25) { () -> Void in
            /*
            闭包被抛出后，必须知道其中的方法和属性属于谁，
            所以要用self
            */
            self.layoutIfNeeded()
        }
        
        
        
    }
}
